package com.example.carrierapp.ui.splash;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;

import com.example.carrierapp.base.BaseActivity;
import com.example.carrierapp.config.ConstValue;
import com.example.carrierapp.ui.splash.guide.GuideActivity;
import com.example.carrierapp.util.ActivityUtil;
import com.example.carrierapp.util.PermisstionHandleUtil;
import com.example.carrierapp.util.SPUtils;
import com.example.lb.fingerdemo.R;

/**
 * An example full-screen activity that shows and hides the system UI (i.e. status bar and
 * navigation/system bar) with user interaction.
 */
public class SplashActivity extends BaseActivity {
    /**
     * Whether or not the system UI should be auto-hidden after {@link #AUTO_HIDE_DELAY_MILLIS}
     * milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after user interaction
     * before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates and a change of the status
     * and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 3000;

    private final Handler mHideHandler = new Handler();
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setNavigationBarColor(Color.TRANSPARENT);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }

            //是否是第一次进入
            if (SPUtils.getBoolean(SplashActivity.this, ConstValue.FIRST_IN, true)) {
                ActivityUtil.startActivity(SplashActivity.this, GuideActivity.class);
                //不为自动登录或者 登录状态未失败 就跳登录界面
            } else if (!SPUtils.getBoolean(SplashActivity.this, ConstValue.AUTO_LOGIN, false) || !SPUtils.getBoolean(SplashActivity.this, ConstValue.LOGIN_STATE, false)) {//自动登录

                ActivityUtil.startLogin(SplashActivity.this, true);
            } else {
                ActivityUtil.startMainActivity(SplashActivity.this);
            }
            finish();
        }
    };

    private View mContentView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getWindow().getDecorView();
    }

    @Override
    public int getContentView() {
        return R.layout.activity_splash;
    }

    @Override
    public String getTitleString() {
        return null;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
//        requestPermissions();
    }

    private void requestPermissions() {
        final String perLoc = Manifest.permission.ACCESS_FINE_LOCATION;
        final String permPhone = Manifest.permission.READ_PHONE_STATE;
        //        final String permStorage = Manifest.permission.WRITE_EXTERNAL_STORAGE;

        final boolean hasLocPerm = ActivityCompat.checkSelfPermission(this, perLoc) == PackageManager.PERMISSION_GRANTED;
        final boolean hasPhonePerm = ActivityCompat.checkSelfPermission(this, permPhone) == PackageManager.PERMISSION_GRANTED;
        //        final boolean hasStoragePerm = ActivityCompat.checkSelfPermission(this,
        // permStorage) == PackageManager.PERMISSION_GRANTED;

        if (hasLocPerm && hasPhonePerm) {
            mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
        } else if (hasLocPerm) {
            ActivityCompat.requestPermissions(this, new String[]{permPhone}, 1);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permPhone, perLoc}, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            boolean passed = true;
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int grantResult = grantResults[i];
                if ((permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) || permission.equals(Manifest.permission.READ_PHONE_STATE)) && grantResult != PackageManager.PERMISSION_GRANTED) {
                    boolean neverAsk = !ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
                    PermisstionHandleUtil.handlePermissionDenied(this, permission, neverAsk, (dialog, which) -> {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            requestPermissions();
                        } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                            mHideHandler.postDelayed(mHidePart2Runnable, 0);
                        }
                    });
                    passed = false;
                    break;
                }
            }
            if (passed) {
                mHideHandler.postDelayed(mHidePart2Runnable, 0);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PermisstionHandleUtil.ACTIVITY_RESULT_CODE) {
            requestPermissions();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHideHandler.removeCallbacksAndMessages(null);
    }
}
